let keyword = '' // 搜索关键字
Page({
  data: {
    showModal: false, // 控制底部弹出层是否显示
    userInfo: {},
    blogList: []
  },

  onLoad() {
    this.getBlogList()
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.setData({
      blogList: []
    })
    keyword = ''
    this.getBlogList()
  },

  // 上拉加载
  onReachBottom() {
    this.getBlogList(this.data.blogList.length)
  },

  // 发布
  onPublish() {
    // 判断用户是否授权
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已授权
          wx.getUserInfo({
            success: data => {
              // console.log(data)
              wx.navigateTo({
                url: `../blog-edit/blog-edit?nickName=${data.userInfo.nickName}&avatarUrl=${data.userInfo.avatarUrl}`,
              })
            }
          })

        } else {
          // 未授权
          this.setData({
            showModal: true
          })
        }
      }
    })
  },

  // 授权成功
  onLoginSuccess(e) {
    this.setData({
      showModal: false
    })
    wx.showToast({
      title: '授权成功'
    })
  },

  // 授权失败
  onLoginFail() {
    wx.showModal({
      title: '授权用户才能发布',
      content: '',
    })
  },

  // 获取博客列表
  getBlogList(start = 0) {
    wx.showLoading({
      title: '拼命加载中...',
    })
    wx.cloud.callFunction({
      name: 'blog',
      data: {
        keyword,
        start,
        count: 6,
        $url: 'list'
      }
    }).then(res => {
      if (res.result.data) {
        this.setData({
          blogList: this.data.blogList.concat(res.result.data)
        })
        wx.hideLoading()
        wx.stopPullDownRefresh()
      }
    })
  },

  // 搜索关键字
  onSearch(e) {
    this.setData({
      blogList: []
    })
    keyword = e.detail.keyword
    this.getBlogList()
  },

  // 进入评论
  onComment(e) {
    wx.navigateTo({
      url: '../blog-comment/blog-comment?blogId=' + e.currentTarget.dataset.blogId,
    })
  },
  onShareAppMessage(e) {
    const blog = e.target.dataset.blog
    return {
      title: blog.content,
      path: `/pages/blog-comment/blog-comment?blogId=${blog._id}`,
      //  imageUrl: blog.img // 分享功能图片不支持云文件ID
    }
  }
})